let app = getApp()

const db = wx.cloud.database({
  env: app.globalData.CLOUD_ENV
})
const DBClassify = db.collection('db_classifys')
const DBShare = db.collection('db_share')
const DBInterview = db.collection('db_topic')
const api = require('../../api/index')
import * as echarts from "../../components/ec-canvas/echarts"
async function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  });
  canvas.setChart(chart);
  let o1 = await DBInterview.where({
    type: '嵌入式'
  }).count();
  let o2 = await DBInterview.where({
    type: 'h5'
  }).count();
  let o3 = await DBInterview.where({
    type: 'java'
  }).count();
  let o4 = await DBInterview.where({
    type: 'php'
  }).count();
  let o5 = await DBInterview.where({
    type: 'python'
  }).count();
  let o6 = await DBInterview.where({
    type: 'net'
  }).count();
  let net_num = o6.total;
  let h5_num = o2.total;
  let lot_num = o1.total;
  let java_num = o3.total;
  let php_num = o4.total;
  let python_num = o5.total;
  // console.log({
  //   net_num,
  //   h5_num,
  //   lot_num,
  //   java_num,
  //   php_num,
  //   python_num
  // })
  var option = {
    backgroundColor: 'rgba(255,255,255,0.8)',
    tooltip: {
      trigger: 'item'
    },
    legend: { //显示图例
      show: true,
      top: '0%',
      left: 'center'
    },
    series: [{
     
      label: {
        normal: {
          fontSize: 14
        }
      },
      type: 'pie',
      center: ['50%', '60%'], //位置
      radius: ['10%', '30%'], //圈大小
      data: [{ //每一项
          value: lot_num,
          name: `嵌入式(${lot_num})`
        }, {
          value: h5_num,
          name: `前端(${h5_num})`
        }, {
          value: java_num,
          name: `java(${java_num})`
        },
        {
          value: php_num,
          name: `php(${php_num})`
        },
        {
          value: python_num,
          name: `python(${python_num})`
        },
        {
          value: net_num,
          name: `网络工程(${net_num})`
        }
      ]
    }]
  };
  chart.setOption(option);
  return chart;
}
Page({
  data: {
    isSigin: false,
    count: 0,
    columns: [
      '嵌入式',
      'h5',
      'java',
      'php',
      'python',
      '网络工程'
    ],
    value: '',
    banners: [{
        id: 1,
        src: "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/banner/banner4.png?sign=c9df27956febc2821014197525072cf2&t=1691587194",
        title: '常见编程词汇',
        msg: 'Common programming vocabulary',
        url: '../cihui/cihui',
        color: '#6492AC'
      },
      {
        id: 2,
        src: "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/banner/banner3.png?sign=0d928c75cf4c3eb571bb6e8de82580b5&t=1691587223",
        title: "程序员简历模板",
        msg: "Programmer resume template",
        url: '../intro/list/list',
        color: '#9ACD56'
      },
      {
        id: 6,
        src: "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/banner/banner2.png?sign=aacd1006d7a040b385d81c34e42a9b5b&t=1691587233",
        title: "查阅企业面试真题",
        url: "/pages/qiye/list/list",
        msg: "Enterprise Interview Questions",
        color: '#EEF9BF',
        // color: '#EE6666',
      },
      {
        id: 3,
        src: "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/banner/banner2.png?sign=aacd1006d7a040b385d81c34e42a9b5b&t=1691587233",
        title: "攻城狮课程大纲",
        msg: "Senior Development Engineer",
        url: '../outline/list/list',
        color: '#CAA6E4'
      },
      {
        id: 4,
        src: "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/banner/banner1.png?sign=b7bfee5561f37d71de069e7784c7672a&t=1691587253",
        title: "在线考试",
        url: "/pages/exam/list/list",
        msg: "Online exam",
        // color: '#FFB3A6',
        color: '#0088FF'
      },
      {
        id: 5,
        src: "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/banner/banner1.png?sign=b7bfee5561f37d71de069e7784c7672a&t=1691587253",
        title: "常用开发软件",
        url: "/pages/toollist/toollist",
        msg: "Development Software",
        color: '#FFB3A6',
        // color: '#EE6666',
      },
     
    ],
    classifys: [],
    num: 0,
    direction: 'x', //x
    nickName: '',
    c: 0,
    toolList: [
      '嵌入式',
      'h5',
      'java',
      'php',
      'python',
      'net'
    ],

    ec: {
      onInit: initChart
    },
  },
  async getCountFn() {
    await api.siginCountFunc().then(
      res => {
        // console.log(res)
        this.setData({
          count: res.total
        })
      }
    )
  },
  async initSiginFn() {
    let dt = new Date();
    let yy = dt.getFullYear();
    let mm = dt.getMonth() + 1;
    let dd = dt.getDate();
    let openid = wx.getStorageSync('openid');
    let that = this;
    if (openid) {
      // 今日是否签到
      await api.querySiginFunc(yy, mm, dd, openid)
        .then(
          content => {
            // console.log('1.0',content)
            if (content.data.length == 0) {
              // 未签到
              this.setData({
                isSigin: false
              })
            } else {
              // 已经签到
              this.setData({
                isSigin: true
              })
            }
          }
        )
    } else {
      // wx.showToast({
      //   title: '请先登录。',
      //   icon: 'none',
      // })
    }


  },
  // 添加签到
  addSiginFn() {
    // console.log(111);
    let dt = new Date();
    let yy = dt.getFullYear();
    let mm = dt.getMonth() + 1;
    let dd = dt.getDate();
    let openid = wx.getStorageSync('openid');
    let that = this;
    if (openid) {
      api.querySiginFunc(yy, mm, dd, openid)
        .then(
          content => {
            // console.log('1.0',content)
            if (content.data.length == 0 && content.errMsg == "collection.get:ok") {
              // 未签到
              api.addSiginFunc(yy, mm, dd, openid)
                .then(
                  rows => {
                    // console.log('2.0',rows)
                    if (rows.errMsg == "collection.add:ok") {
                      that.setData({
                        isSigin: true
                      })
                      that.getCountFn();
                    } else {
                      wx.showToast({
                        title: '签到失败。',
                        icon: 'none'
                      })
                    }

                  }
                )
            } else {
              // 已经签到
              wx.showToast({
                title: '今日已签到。',
                icon: 'none',
              })
            }
          }
        )
    } else {
      wx.showToast({
        title: '请先登录再签到',
        icon: 'none',
      })
    }
  },
  // tab选项卡
  addTabFn(event) {
    let c = event.currentTarget.dataset.c;
    // console.log({c})
    this.setData({
      c
    })
  },
  showListFn() {
    let direction = this.data.direction;
    if (direction == 'y') {
      direction = 'x';
    } else {
      direction = 'y';
    }
    this.setData({
      direction
    })
  },
  onChange(event) {
    // event.detail 为当前输入的值
    // console.log(event.detail);
  },
  getNum(e) {
    let current = e.detail.current;
    // console.log(e)
    this.setData({
      num: current
    })
  },
  // 监听输入框获取焦点
  onFocus() {
    // console.log('test')
    // 跳转搜索页面
    wx.navigateTo({
      url: '../search/search',
    })
  },
  // 分类列表
  async listClassifyFn() {
    let that = this;
    await DBClassify.get()
      .then(
        content => {
          // console.log('3.0', content)
          if (content.data) {
            that.setData({
              classifys: content.data
            })
          }
        }
      )
  },
  // 加载页面的回调函数
  onLoad(option) {
    this.listClassifyFn()
    this.initSiginFn()
    this.getCountFn()
    // console.log('1.0',option)
    if (option) {
      let {
        code
      } = option;
      if (code) {
        wx.setStorageSync('code', code)
        wx.redirectTo({
          url: '../user/login/login',
        })
      }
    }
  },
  async addShareFnTo(openid, code) {
    await DBShare.where({
      to_user_id: openid
    }).get().then(
      async rows => {
        let {
          data
        } = rows;
        if (data.length == 0) {
          await DBShare.add({
              data: {
                code,
                to_user_id: openid,
                from_user_id: code,
                create_time: new Date().getTime()
              }
            })
            .then(
              rows => {
                // console.log(rows)
              }
            )
        }
      }
    )
  },
  onShow() {
    this.listClassifyFn()
    this.initSiginFn()
    this.getCountFn()
    let openid = wx.getStorageSync('openid')
    let code = wx.getStorageSync('code')
    let nickName = wx.getStorageSync('nickName')
    if (nickName) {
      this.setData({
        nickName
      })
    }
    if (openid) {
      if (code) {
        this.addShareFnTo(openid, code); // 标记分享目标
      }
    }
  },
  onShareAppMessage() {
    let user_id = wx.getStorageSync('user_id')
    return {
      title: '掌上刷题宝',
      path: "pages/index/index?code=" + user_id
      // ,
      // imageUrl: 'https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/banner/banner4.png?sign=c9df27956febc2821014197525072cf2&t=1691587194'
    }
  },
  onShareTimeline() {
    let user_id = wx.getStorageSync('user_id')
    return {
      title: '掌上刷题宝',
      query: 'code=' + user_id
    }
  }
});